package com.CampaignManager.client;

import com.CampaignManager.shared.PlayerCityDTO;
import com.CampaignManager.shared.PlayerDTO;
import com.CampaignManager.shared.ResourceAmountDTO;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class SpendEspionageForm extends Composite {

	private static SpendEspionageFormUiBinder uiBinder = GWT
			.create(SpendEspionageFormUiBinder.class);

	interface SpendEspionageFormUiBinder extends
			UiBinder<Widget, SpendEspionageForm> {
	}

	public SpendEspionageForm() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField
	FlexTable playerExploitTable;
	
	public void RefreshTable(final String cityName, final PlayerDTO playerInfo, final CampaignManager mainForm, final ResourceForm resForm) {
		
		final PlayerCityDTO city = playerInfo.getCity(cityName);
		
		playerExploitTable.removeAllRows();
		
		playerExploitTable.setText(0, 0, "Exploit "+cityName);		
		playerExploitTable.getRowFormatter().addStyleName(0, "watchListHeader");
		playerExploitTable.addStyleName("watchList");
		
		playerExploitTable.setText(1, 0, "Favor: ");
		playerExploitTable.setText(1, 1, city.getFavor().toString());
		
		playerExploitTable.setText(2, 0, "Leverage: ");
		playerExploitTable.setText(2, 1, city.getLeverage().toString());
		
		playerExploitTable.setText(3, 0, "Extort for "+city.getLeverage()*PlayerDTO.GOLD_PER_LEVERAGE+" gold");
		Button extort = new Button("Extort");
		extort.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				mainForm.campaignService.Extort(cityName, new AsyncCallback<Void>() {
					@Override
					public void onSuccess(Void result) {
						ResourceAmountDTO gold = playerInfo.getResource("Gold");
						gold.setAmount(gold.getAmount()+(city.getLeverage()*PlayerDTO.GOLD_PER_LEVERAGE));
						city.setFavor(-city.getLeverage());
						city.setLeverage(0L);
						resForm.RefreshTable(playerInfo);
						RefreshTable(cityName, playerInfo, mainForm, resForm);
					}					
					@Override
					public void onFailure(Throwable caught) {
						mainForm.handleError(caught);
					}
				});
			}
		});
		if (city.getLeverage() <= 0L) {
			extort.setEnabled(false);
			extort.setTitle("no leverage...");
		}
		playerExploitTable.setWidget(3, 1, extort);		
	}
}
